package com.cheyun.netsalev3.utils.api;


import com.cheyun.netsalev3.MyApplication;
import com.cheyun.netsalev3.utils.LogInterceptor;
import com.cheyun.netsalev3.utils.api.gsonDeserialize.ArraySecurityAdapter;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.List;
import java.util.concurrent.TimeUnit;
import com.google.gson.GsonBuilder;
import com.google.gson.Gson;


public class NoticeApiClient {
    /**
     * Http连接超时
     */
    private Integer CONNECT_TIMEOUT = 20;

    /**
     * Http 读取超时
     */
    private Integer READ_TIMEOUT = 20;

    /**
     * Http 写入超时
     */
    private Integer WRITE_TIMEOUT = 20;

    /**
     * 缓存大小
     */
    private Integer CACHE_SIZE = 10 * 1024 * 1024;

    private DmApiStores retrofit(){
        Cache cache = new Cache(MyApplication.getInstance().getCacheDir(),CACHE_SIZE);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .cache(cache);
        builder.addInterceptor(new LogInterceptor());
        OkHttpClient okHttpClient = builder.build();
        Gson gson = new GsonBuilder().registerTypeAdapter(List.class,new ArraySecurityAdapter()).create();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(DmApiStores.NOTICE_API_SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit.create(DmApiStores.class);
    }

    public static DmApiStores getInstance() {
        return mInstance.retrofit();
    }

    private static NoticeApiClient mInstance = new NoticeApiClient();

}
